/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-05-10
*/
package com.rzico.basics.service;

import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Company;
import com.rzico.basics.entity.CompanyEmployee;
import com.rzico.basics.entity.Member;
import com.rzico.basics.model.CompanyEmployeeVo;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysUserService;
import com.rzico.util.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.basics.mapper.CompanyEmployeeMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 企业员工业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class CompanyEmployeeService extends BaseServiceImpl<CompanyEmployee, String> {

    @Autowired
    private CompanyEmployeeMapper companyEmployeeMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CompanyService companyService;

    @Override
    public BaseMapper<CompanyEmployee, String> getMapper() {
        return companyEmployeeMapper;
    }

    /**
     * 统计当前公司员工数量
     * @return true：被引用，false：未被引用
     */
    public int countCompanyEmployeeNum(Map<String,Object> params) {
        return companyEmployeeMapper.selectRowCount(params);
     }

    //条件查询某个企业的员工
    public List<CompanyEmployeeVo> selectCompanyEmployeeVoList(Map<String, Object> params){
        List<CompanyEmployeeVo> list = companyEmployeeMapper.selectCompanyEmployeeVoList(params);
        for (CompanyEmployeeVo c : list) {
            if (null == c.getWelfareBalance()) {
                c.setWelfareBalance(BigDecimal.ZERO);
            }
        }
        return list;
    }

    //查询企业的某个员工信息
    public CompanyEmployeeVo findById(Map<String,Object> params) {
        List<CompanyEmployeeVo> list = selectCompanyEmployeeVoList(params);
        if (list.size()>0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    public CompanyEmployeeVo findByMobile(Map<String,Object> params) {
        List<CompanyEmployeeVo> list = selectCompanyEmployeeVoList(params);
        if (list.size()>0) {
            return list.get(0);
        } else {
            return null;
        }
    }


    /**
     * 修改企业员工的信息
     */
    public int update(CompanyEmployeeVo companyEmployeeVo){
        //Member member = new Member();
        CompanyEmployee companyEmployee = new CompanyEmployee();
        companyEmployee.setId(companyEmployeeVo.getId());

        if (null != companyEmployeeVo.getStatus()) {
            companyEmployee.setStatus(companyEmployeeVo.getStatus());
        }
        if (null != companyEmployeeVo.getJob()) {
            companyEmployee.setJob(companyEmployeeVo.getJob());
        }

        if (null != companyEmployeeVo.getEmpName()) {
            companyEmployee.setEmpName(companyEmployeeVo.getEmpName());
        }

        if (null != companyEmployeeVo.getEmpNo()) {
            companyEmployee.setEmpNo(companyEmployeeVo.getEmpNo());
        }


        if (null != companyEmployeeVo.getSex()) {
            companyEmployee.setSex(companyEmployeeVo.getSex());
        }


        Integer row = 0;

        row = super.updateByPrimaryKeySelective(companyEmployee);

        return row;

    }

    /**
     * 导入员工信息前，解除员工与之前公司的绑定关系，设为离职状态
     * @param list
     * @param companyId
     */
    public void cancelCompanyBinding(List<CompanyEmployeeVo> list, String mchId, long enterpriseId, Long companyId){
        for (CompanyEmployeeVo cm : list) {
            //处理 手机号导入
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("mobile", cm.getMobile());
            param.put("mchId", mchId);
            param.put("enterpriseId", enterpriseId);
            List<Member> member = memberService.selectList(param);
            if (0 < member.size()) {
                Map<String,Object> params = new HashMap<>();
                params.put("memberId",member.get(0).getId());
                params.put("enterpriseId", enterpriseId);
                List<CompanyEmployee> cList = super.selectList(params);
                for (CompanyEmployee c : cList) {
                    if (companyId != c.getCompanyId()) {
                        c.setStatus(2);
                        super.updateByPrimaryKey(c);
                    }
                }
            }
        }
    }

    /**
     * 先检验导入企业员工得信息,验证每一条信息是否可以导入，若验证未通过，将错误信息返回
     * 验证通过后，导入员工信息
     * 导入结果描述，0.可导入，1.当前员工已在企业处于在职状态，2.当前员工在企业处于在职状态，3.member表存在记录，但无企业关联
     */
    @Transactional(rollbackFor = Exception.class)
    public List<CompanyEmployeeVo> upload(List<CompanyEmployeeVo> list, String mchId, long enterpriseId, Long companyId){

        List<CompanyEmployeeVo> resultlist = new ArrayList<CompanyEmployeeVo>();
        for (CompanyEmployeeVo cm : list) {

            if (cm.getMobile()!=null && !"".equals(cm.getMobile())) {
                //处理 手机号导入
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("mobile", cm.getMobile());
                param.put("mchId", mchId);
                param.put("enterpriseId", enterpriseId);
                List<Member> member = memberService.selectList(param);
                Member m = new Member();
                if (0 == member.size()) {
                    //先插入企业用户信息插入member，若member已存在该员工信息，不执行插入操作，
                    m.setCreateDate(new Date());
                    m.setUsername(CodeGenerator.getUUID());
                    m.setMchId(mchId);
                    m.setDeleted(false);
                    m.setMobile(cm.getMobile());
                    m.setPhone(cm.getPhone());
                    m.setName(cm.getName());
                    m.setVip(cm.getVip());
                    m.setEnterpriseId(enterpriseId);
                    m.setBalance(BigDecimal.ZERO);
                    m.setFreezeBalance(BigDecimal.ZERO);
                    m.setAmount(BigDecimal.ZERO);
                    m.setPoint(0L);
                    m.setMemberType(0);
                    m.setGender(2);
                    m.setTaxType(0);
                    m.setCompanyId(companyId);
                    memberService.createMember(m);
                } else {
                    m.setId(member.get(0).getId());
                    m.setName(cm.getName());
                    m.setVip(cm.getVip());
                    m.setCompanyId(companyId);
                    memberService.updateByPrimaryKeySelective(m);
                }

                Map<String,Object> params = new HashMap<>();
                params.put("companyId",companyId);
                params.put("mobile",cm.getMobile());
                params.put("enterpriseId", enterpriseId);
                CompanyEmployeeVo memberResult = findByMobile(params);

                /**
                 * 若员工表已存在信息，不执行插入，更新员工信息，再执行企业与员工关联
                 * 若员工表不存在信息，先插入员工信息，再执行企业与员工关联
                 * 若为原到位离职员工，则更新数据即可
                 */
                if (null == memberResult){

                    //再插入员工与企业关联信息，companyEmployee表
                    CompanyEmployee companyEmployee = new CompanyEmployee();
                    companyEmployee.setCompanyId(companyId);
                    companyEmployee.setMemberId(m.getId());
                    companyEmployee.setJob(cm.getJob());
                    companyEmployee.setEmpName(cm.getName());
                    companyEmployee.setEmpNo(cm.getEmpNo());
                    companyEmployee.setSex(cm.getSex());
                    companyEmployee.setStatus(1);
                    companyEmployee.setEnterpriseId(enterpriseId);
                    super.insertUseGeneratedKeys(companyEmployee);
                } else {
                    CompanyEmployee companyEmployee = selectByPrimaryKey(memberResult.getId());

                    companyEmployee.setCompanyId(companyId);
                    companyEmployee.setMemberId(m.getId());
                    companyEmployee.setJob(cm.getJob());
                    companyEmployee.setEmpName(cm.getEmpName());
                    companyEmployee.setEmpNo(cm.getEmpNo());
                    companyEmployee.setSex(cm.getSex());
                    companyEmployee.setStatus(1);
                    companyEmployee.setEnterpriseId(enterpriseId);
                    super.updateByPrimaryKeySelective(companyEmployee);
                }

                resultlist.add(cm);
            } else {
                Map<String,Object> params = new HashMap<>();
                params.put("companyId",companyId);
                params.put("empNo",cm.getEmpNo());
                params.put("empName",cm.getEmpName());
                params.put("enterpriseId", enterpriseId);
                CompanyEmployeeVo memberResult = findByMobile(params);

                /**
                 * 若员工表已存在信息，不执行插入，更新员工信息，再执行企业与员工关联
                 * 若员工表不存在信息，先插入员工信息，再执行企业与员工关联
                 * 若为原到位离职员工，则更新数据即可
                 */
                if (null == memberResult){

                    //再插入员工与企业关联信息，companyEmployee表
                    CompanyEmployee companyEmployee = new CompanyEmployee();
                    companyEmployee.setCompanyId(companyId);
                    companyEmployee.setJob(cm.getJob());
                    companyEmployee.setEmpName(cm.getEmpName());
                    companyEmployee.setEmpNo(cm.getEmpNo());
                    companyEmployee.setStatus(1);
                    companyEmployee.setSex(cm.getSex());
                    companyEmployee.setEnterpriseId(enterpriseId);
                    super.insertUseGeneratedKeys(companyEmployee);
                } else {
                    CompanyEmployee companyEmployee = selectByPrimaryKey(memberResult.getId());

                    companyEmployee.setCompanyId(companyId);
                    companyEmployee.setJob(cm.getJob());
                    companyEmployee.setEmpName(cm.getEmpName());
                    companyEmployee.setEmpNo(cm.getEmpNo());
                    companyEmployee.setSex(cm.getSex());
                    companyEmployee.setStatus(1);
                    companyEmployee.setEnterpriseId(enterpriseId);
                    super.updateByPrimaryKeySelective(companyEmployee);
                }

                resultlist.add(cm);
            }



        }
        return resultlist;
    }



    /**
     *  检验企业员工列表信息是否符合要求
     *
     * 先用手机号查询member表，若不存在可以导入信息，保存member，再companyid将企业与员工进行关联；
     * 若存在暂不做任何处理，再去查询company_employee，
     * 1若当前企业存在该member记录,状态为在职,已存在，不导入
     * 2若当前企业存在该member记录，状态为离职，状态修改为在职
     * 3若其他企业存在该member记录，状态为在职，不导入，提示该员工已在其他企业任职
     * 4若其他企业存在该member记录，状态为离职，在当前企业加入该员工
     * 5若未查找到记录，可以导入
     *
     * 在手机号输入错误的情况下（人为因素），进行一次上面的操作
     * @param list
     * @param enterpriseId
     * @param companyId
     * @return
     */
    public Map<String,Object> checkCompanyEmployee(List<CompanyEmployeeVo> list, String mchId, Long enterpriseId, Long companyId){
        Map<String, Object> result = new HashMap<String, Object>();

        result.put("returnCode","success");
        for (CompanyEmployeeVo cm : list) {
            if (cm.getMobile()!=null && !"".equals(cm.getMobile())) {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("mobile", cm.getMobile());
                param.put("mchId", mchId);
                param.put("enterpriseId", enterpriseId);
                List<Member> member = memberService.selectList(param);
                if (0 < member.size()) {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("memberId", member.get(0).getId());
                    params.put("status", 1);
                    params.put("enterpriseId", enterpriseId);
                    List<CompanyEmployee> employeeList = selectList(params);
                    for (CompanyEmployee companyEmployee:employeeList) {
                        if (!companyEmployee.getCompanyId().equals(companyId) ) {
                            Company company = companyService.selectByPrimaryKey(companyEmployee.getCompanyId());
                            cm.setResult(company.getName() + "已存在该手机号,请先离职");
                            result.put("returnCode","error");
                            break;
                        } else {
                            result.put("returnCode","error");
                            cm.setResult("本公司已存在该手机号");
                            break;
                        }
                    }
                }
            } else {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("empNo", cm.getEmpNo());
                param.put("empName", cm.getEmpName());
                param.put("mchId", mchId);
                param.put("status", 1);
                param.put("enterpriseId", enterpriseId);
                List<CompanyEmployee> companyEmployeeList = companyEmployeeMapper.selectList(param);
                if (0 < companyEmployeeList.size()) {
                    CompanyEmployee companyEmployee = companyEmployeeList.get(0);
                    if (!companyEmployee.getCompanyId().equals(companyId)) {
                        Company company = companyService.selectByPrimaryKey(companyEmployee.getCompanyId());
                        cm.setResult(company.getName() + "已存在该员工,请先离职");
                        result.put("returnCode", "error");
                        break;
                    } else {
                        result.put("returnCode", "error");
                        cm.setResult("本公司已存在该员工");
                        break;
                    }

                }
            }
        }
        result.put("vo",list);
        return result;
    }

}
